using System.Collections.ObjectModel;
using System.Windows;

using HelpDeskTool.Entities;
using HelpDeskTool.Extensions;
using HelpDeskTool.Services;
using HelpDeskTool.Views;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace HelpDeskTool;

public partial class App : Application
{
	private readonly ILogger logger;
	private readonly CancellationTokenSource cancellationTokenSource;
	private readonly Task updaterTask;

	public App()
	{
		cancellationTokenSource = new();

		var computers = new ObservableCollection<IComputer>();
		var viewModel = new ViewModel(computers);

		using var serviceProvider = new ServiceCollection()
			.AddSingleton<MainWindow>()
			.AddSingleton(_ => viewModel)
			.AddLogging(x => x.AddSimpleConsole())
			.RegisterMyServices()
			.BuildServiceProvider(true);

		var mainWindow = serviceProvider.GetRequiredService<MainWindow>();
		mainWindow.Show();

		logger = serviceProvider.GetRequiredService<ILogger<App>>();
		var updater = serviceProvider.GetRequiredService<IUpdater>();
		var period = TimeSpan.FromMinutes(1);

		updaterTask = updater.StartAsync(computers, period, cancellationTokenSource.Token);
		updater.InformationChanged += viewModel.InformationChanged;
	}

	protected override void OnExit(ExitEventArgs e)
	{
		cancellationTokenSource.Cancel();

		try
		{
			updaterTask.Wait(); // async await not wait task
		}
		catch (OperationCanceledException) { } // ignore cancelled
		catch (AggregateException ae)
		{
			foreach (var ie in ae.Flatten().InnerExceptions.Where(x => x is not OperationCanceledException))
				logger.LogException(ie);
		}
		catch (Exception ex)
		{
			logger.LogException(ex);
		}

		cancellationTokenSource.Dispose();

		base.OnExit(e);
	}
}
